package org.xfg.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xfg.domain.active.model.entity.SkuRechargeEntity;
import org.xfg.domain.active.service.IRaffleActivityAccountQuotaService;
import org.xfg.domain.rebate.event.SendRebateMessageEvent;
import org.xfg.domain.rebate.model.valobj.RebateTypeVO;
import org.xfg.types.enums.ResponseCode;
import org.xfg.types.event.BaseEvent;
import org.xfg.types.exception.AppException;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * 监听用户行为返利消息
 */
@Slf4j
@Component
public class RebateMessageCustomer {

    @Value("${spring.rabbitmq.topic.send_rebate}")
    private String topic;

    @Resource
    private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_rebate}"))
    public void lister(String message){
        try {
            log.info("监听用户行为返利消息 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> eventMessage  =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage>>() {}.getType());
            SendRebateMessageEvent.RebateMessage rebateMessage = eventMessage.getData();
            if (!RebateTypeVO.SKU.getCode().equals(rebateMessage.getRebateType())) {
                log.info("监听用户行为返利消息 - 非sku奖励暂时不处理 topic: {} message: {}", topic, message);
                return;
            }

            // 入账记录
            SkuRechargeEntity req = new SkuRechargeEntity();
            req.setUserId(rebateMessage.getUserId());
            req.setSku(Long.parseLong(rebateMessage.getRebateConfig()));
            req.setOutBusinessNo(rebateMessage.getBizId()+ UUID.randomUUID().toString().substring(0,6));
            raffleActivityAccountQuotaService.createOrder(req);
        }catch (AppException e){
                log.warn("监听用户行为返利消息，消费重复 topic: {} message: {}", topic, message, e);
                return;
        }
        catch (Exception e){
            log.error("监听用户行为返利消息，消费失败 topic: {} message: {}", topic, message, e);
            return;
        }

    }

}
















